/*
 * @Author: 13177709051 3506463075@qq.com
 * @Date: 2024-10-30 21:12:47
 * @LastEditors: 13177709051 3506463075@qq.com
 * @LastEditTime: 2024-10-30 22:16:48
 * @FilePath: /linux27/test_thread/Thread.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>
#include <string>
#include <pthread.h>

namespace ThreadMoudle
{
    //线程要执行的方法, 后面可以随时调正
    typedef void (*func_t)(const std::string &name); //函数指针类型
    class Thread
    {
    public:
        void Excute()
        {
            std::cout << _name << "is running" << std::endl;
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }
    public:
        Thread(const std::string &name, func_t func) :_name(name), _func(func)
        {
            std::cout << "create" << name << " done" << std::endl;
        }
        static void *ThreadRoutine(void *args)//线程都会执行该方法
        {
            Thread *self = static_cast<Thread*>(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = ::pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if(n != 0) return false;
            return true;
        }
        std::string Status()
        {
            if(_isrunning) return "running";
            else return "sleep";
        }
        void Stop()
        {
            if(_isrunning)
            {
                ::pthread_cancel(_tid);
                _isrunning = false;
                std::cout << _name << " Stop" << std::endl;
            }
        }
        void Join()
        {
            ::pthread_join(_tid, nullptr);
            std::cout << _name << "Joined" << std::endl;
        }
        std::string Name()
        {
            return _name;
        }
        ~Thread()
        {
            
        }
    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func; //线程要执行的回调函数
    };
}//namespace ThreadModle
